<template>
  <div class="common-layout">
    <Header/>
    <el-container id="container">
      <el-main>
        <div id="selectSeat">
          <div id="seatDemo">
            <div class="seat">
              <el-image :src="imgPrefix+'/other/canSelectSeat.png'" style="width:39px;height:37px;"/>
              <el-text size="large" tag="b">可选座位</el-text>
            </div>
            <div class="seat">
              <el-image :src="imgPrefix+'/other/haveSoldSeat.png'" style="width:39px;height:37px;"/>
              <el-text size="large" tag="b">已售座位</el-text>
            </div>
            <div class="seat">
              <el-image :src="imgPrefix+'/other/haveSelectSeat.png'" style="width:39px;height:37px;"/>
              <el-text size="large" tag="b">已选座位</el-text>
            </div>
          </div>
          <div id="screenDemo">
            <el-text size="large" tag="b">{{ organizeInfo.hallName }}</el-text>
            <el-text size="large" tag="b">银幕中央</el-text>
          </div>
          <div id="rowNumShow">
            <el-text size="large" tag="b" v-for="rowNum in organizeInfo.rowNo">
              {{ rowNum }}
            </el-text>
          </div>
          <div id="seatAll" v-for="rowIndex in organizeInfo.rowNo">
            <el-image :src="getImageSrc(rowIndex, lineIndex)" style="width:39px;height:37px;"
                      v-for="lineIndex in organizeInfo.lineNo" @click="clickSelectSeat(rowIndex, lineIndex)"/>
          </div>
        </div>
        <div id="movieInfoAndBuyTicket">
          <el-image :src="imgPrefix+organizeInfo.mPic" fit="cover" style="width: 60%;float:left;margin-right:20px;"/>
          <div id="movieDescription">
            <el-form style="margin-top: 20px" v-model="organizeInfo" size="large">
              <el-form-item>
                <el-text style="font-weight:bold;font-size: 30px">{{ organizeInfo.movieName }}</el-text>
              </el-form-item>
              <el-form-item label="类型：" style="margin-top: 100px;">
                <el-text>
                  <el-tag size="small" style="font-weight:bold;">{{ organizeInfo.mtName }}</el-tag>
                </el-text>
              </el-form-item>
              <el-form-item label="时长：">
                <el-text tag="b">{{ organizeInfo.mDuration }}分钟</el-text>
              </el-form-item>
            </el-form>
          </div>
          <div id="organizeInfo" style="margin-top: 100px">
            <el-form style="margin-top: 20px" v-model="organizeInfo" size="large">
              <el-form-item label="影院：">
                <el-text style="font-weight:bold;">{{ organizeInfo.cinemaName }}</el-text>
              </el-form-item>
              <el-form-item label="影厅：">
                <el-text style="font-weight:bold;">{{ organizeInfo.hallName }}</el-text>
              </el-form-item>
              <el-form-item label="场次：">
                <el-text style="font-weight:bold;">{{ organizeInfo.beginTime }}</el-text>
              </el-form-item>
              <el-form-item label="票价：">
                <el-text style="font-weight:bold;">{{ organizeInfo.price }}元</el-text>
              </el-form-item>
              <el-divider/>
              <el-form-item label="座位：" size="default">
                <div id="selectSeatList">
                  <div class="ticketDiv" v-for="selectSeat in selectSeatList">
                    <el-text size="large">
                      {{ selectSeat.rowIndex }}排{{ selectSeat.lineIndex }}座
                    </el-text>
                  </div>
                </div>
              </el-form-item>
              <el-divider/>
              <el-form-item label="总价：">
                <el-text>￥{{ selectSeatList.length * organizeInfo.price }}元</el-text>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="doPay" size="small">确认选座</el-button>
              </el-form-item>
            </el-form>
            <div id="isPaid">
              <el-dialog
                  v-model="isPaidDialog"
                  title="请支付订单！"
                  width="500"
                  align-center
              >
                <span>订单创建成功，请在新打开的窗口中支付！</span>
                <template #footer>
                  <div class="dialog-footer">
                    <el-button @click="doPay">重新打开付款窗口</el-button>
                    <el-button type="primary" @click="checkIsPaid">我已付款</el-button>
                  </div>
                </template>
              </el-dialog>
            </div>
          </div>
        </div>
      </el-main>
    </el-container>
  </div>
</template>
<script setup>
import {ElNotification, ElMessageBox} from "element-plus";
import request from "@/request.js";
import {request2} from "@/request.js";
import qs from 'qs'
import {ref, reactive, onMounted, inject} from "vue";
import {Lock, User, Cellphone, UserFilled, Search, StarFilled} from "@element-plus/icons-vue";
import SessionStorage from "@/SessionStorage.js";
import {useRoute, useRouter} from "vue-router";
import axios from "axios";
import moment from "moment";

const imgPrefix = inject('imgPrefix');
const baseIp = import.meta.env.VITE_APP_API_URL;


const router = useRouter();
const loginUser = SessionStorage.getItem("loginUser");

const route = useRoute();
const soIdWith = route.params.soId;
console.log("从电影场次选择跳转之后，携带的soId为：" + soIdWith);

// 查询场次信息
const organizeInfo = reactive({
  soId: null,
  hId: null,
  mid: null,
  beginTime: null,
  endTime: null,
  price: null,
  leftSeat: null,
  mtName: null,
  releaseAt: null,
  movieName: null,
  fgName: null,
  mDuration: null,
  mPic: null,
  mStatus: null,
  cId: null,
  cinemaName: null,
  hallName: null,
  hCapacity: null,
  rowNo: null,
  lineNo: null,
});
// 查询座位购买信息
const queryDto = reactive({
  hsId: null,
  hId: null,
  rowIndex: null,
  lineIndex: null,
  pageNo: null,
  pageSize: null
})
const hallInfoList = reactive([{
  hsId: null,
  hId: null,
  rowIndex: null,
  lineIndex: null,
  value: null,
}]);
// 获取场次详细信息
axios.post(
    baseIp + ":9091/organize/getOrganizeById?soId=" + soIdWith,
    null,
    {headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'}}
).then(res => {
  console.log(res.data);
  if ('200' === res.data.code && res.data.data != null) {
    console.log("场次详细信息：" + JSON.stringify(res.data.data));
    const organizeInfoQuery = res.data.data;
    organizeInfo.soId = organizeInfoQuery.soId;
    organizeInfo.hId = organizeInfoQuery.hId;
    organizeInfo.mid = organizeInfoQuery.mid;
    organizeInfo.beginTime = organizeInfoQuery.beginTime;
    organizeInfo.endTime = organizeInfoQuery.endTime;
    organizeInfo.price = organizeInfoQuery.price;
    organizeInfo.leftSeat = organizeInfoQuery.leftSeat;

    organizeInfo.mtName = organizeInfoQuery.mtName;
    organizeInfo.movieName = organizeInfoQuery.movieName;
    organizeInfo.releaseAt = organizeInfoQuery.releaseAt;
    organizeInfo.fgName = organizeInfoQuery.fgName;
    organizeInfo.mDuration = organizeInfoQuery.mDuration;
    organizeInfo.mPic = organizeInfoQuery.mPic;
    organizeInfo.mStatus = organizeInfoQuery.mStatus;

    organizeInfo.cId = organizeInfoQuery.cId;
    organizeInfo.cinemaName = organizeInfoQuery.cinemaName;

    organizeInfo.hallName = organizeInfoQuery.hallName;
    organizeInfo.hCapacity = organizeInfoQuery.hCapacity;
    organizeInfo.rowNo = organizeInfoQuery.rowNo;
    organizeInfo.lineNo = organizeInfoQuery.lineNo;
    console.log("传值后的场次详细信息：" + JSON.stringify(organizeInfo));
    queryDto.hId = organizeInfoQuery.hId;
    getHallInfo();
  } else {
    console.log('查询场次信息失败！');
    ElNotification({
      type: 'error',
      message: res.data.msg
    })
  }
})


// 查询场次座位信息
const getHallInfo = () => {
  console.log("queryDto的hId为：" + queryDto.hId)
  axios.post(
      baseIp + ":9091/hallSeat/selectCondition",
      queryDto,
      {headers: {'Content-Type': 'application/json;charset=utf-8'}}
  ).then(res => {
    if ('200' === res.data.code && res.data.data != null) {
      console.log('查询场次座位信息成功！');
      console.log('查询场次座位信息接口返回的数据：', res.data.data);
      const hallInfoQuery = res.data.data.list;
      hallInfoList.splice(0, hallInfoList.length);
      hallInfoList.push(...hallInfoQuery);
    }
  })
}


// 根据行索引、列索引去查找对应的状态值，进而返回对应的图片src
const getImageSrc = (rowIndex, lineIndex) => {
  // console.log("该座位的rowIndex:" + rowIndex + "，该座位的lineIndex:" + lineIndex);
  const targetSeat = hallInfoList.find(seat => seat.rowIndex === rowIndex && seat.lineIndex === lineIndex);
  if (targetSeat) {
    switch (targetSeat.value) {
      case -1:
        return imgPrefix + '/other/haveSelectSeat.png';
      case 0:
        return imgPrefix + '/other/canSelectSeat.png';
      case 1:
        return imgPrefix + '/other/haveSoldSeat.png';
    }
  }


};
const selectSeatList = reactive([]);
const sumAmount = ref(0.00);
// 点击选中，再点击取消选中
const clickSelectSeat = (rowIndex, lineIndex) => {

  const targetSeat = hallInfoList.find(seat => seat.rowIndex === rowIndex && seat.lineIndex === lineIndex);
  if (targetSeat) {
    switch (targetSeat.value) {
      case -1:
        targetSeat.value = 0;
        // 从选中改为未选中，删除元素
        console.log("从选中改为未选中，删除元素:" + rowIndex + "," + lineIndex)
        const index = selectSeatList.findIndex(item => item.rowIndex === rowIndex && item.lineIndex === lineIndex);
        selectSeatList.splice(index, 1);
        break;
      case 0:
        targetSeat.value = -1;
        // 从未选中改为选中，添加元素
        console.log("从未选中改为选中，添加元素:" + rowIndex + "," + lineIndex)
        selectSeatList.push({
          rowIndex: rowIndex,
          lineIndex: lineIndex
        })
        break;
    }
  }

  console.log("selectSeatList中的元素：" + JSON.stringify(selectSeatList));
  console.log(">>> 选中元素个数为：" + selectSeatList.length);
  console.log(">>> 元素价格为：" + organizeInfo.price);
  console.log(">>> 总价格为：" + selectSeatList.length * organizeInfo.price);
  sumAmount.value = selectSeatList.length * organizeInfo.price;
  console.log(">>> 总价格为：" + sumAmount.value);
}

const createDto = reactive({
  uid: null,
  hid: null,
  cId: null,
  soId: null,
  amount: null,
  seatList: [],
})
const doPay = () => {
  createDto.uid = loginUser.uid;
  createDto.hid = organizeInfo.hId;
  createDto.cId = organizeInfo.cId;
  createDto.soId = soIdWith;
  createDto.amount = sumAmount.value;
  selectSeatList.forEach(seat => {
    createDto.seatList.push(seat.rowIndex + "-" + seat.lineIndex);
  })

  console.log("发送支付请求的参数：" + JSON.stringify(createDto));
  request({
    url: "/alipay/pay",
    method: "post",
    data: createDto
  }).then(res => {
    if (res) {
      const alipay = window.open('', '_blank');
      if (alipay) {
        alipay.document.open();
        alipay.document.write(res.toString());
        alipay.document.close();

        isPaidDialog.value = true;
      }
    }
  })
}
const isPaidDialog = ref(false);
const orderVoList = reactive([{
  oid: null,
  uid: null,
  cId: null,
  soId: null,
  cinemaName: null,
  hallName: null,
  seat: null,
  movieName: null,
  beginTime: null,
  endTime: null,
  oCreatedAt: null,
  payAt: null,
  amount: null,
  orderStatus: null,
  orderNo: null,
  qrCodeValue: null,
}])
const checkIsPaid = () => {
  const queryDto = reactive({
    uid: loginUser.uid,
    cId: organizeInfo.cId,
    hId: organizeInfo.hId,
    movieName: null,
    seatList: createDto.seatList,
    beginDay: null,
    endDay: null,
    pageNo: 1,
    pageSize: organizeInfo.hCapacity
  })
  console.log("发送查询订单请求的参数：" + JSON.stringify(queryDto));
  request2({
    url: "/order/selectCondition",
    method: "post",
    data: queryDto
  }).then(res => {
    if (res.code === '200' && res.data != null) {
      console.log("查询订单成功！");
      orderVoList.splice(0, orderVoList.length);
      orderVoList.push(...res.data.list);
      const flag = ref(true);
      for (const i in orderVoList) {
        if (orderVoList[i].orderStatus !== '20') {
          flag.value = false;
          break;
        }
      }
      if (flag.value === false) {
        ElNotification.error("订单未支付，请点击重新打开支付窗口进行支付！")
      } else {
        // 关闭对话框，提示用户去订单中查看电影券码
        isPaidDialog.value = false;
        ElNotification.success("订单支付成功！请点击右上角头像→查看订单中查看券码！");
        router.push("/buySuccess")
      }
    }
  })
}
</script>
<style scoped>
#container {
  height: 100vh;
}

.el-main {
  display: flex;
}

#selectSeat {
  width: 80%;
}

#seatDemo {
  display: flex;
  justify-content: space-around;
  margin: 0 200px;
}

.seat {
  display: flex;
  height: 3%;
}

.seat .el-text {
  margin-left: 20px;
  display: inline;
  margin-top: 8px;
}

#screenDemo {
  margin: 50px auto 50px auto;
  width: 1500px;
  height: 200px;
  border-radius: 50% 50% 50% 50%;
  background: radial-gradient(60% 150px at center bottom, transparent 100%, #b0abab 0) center bottom;
}

#screenDemo .el-text {
  display: flex;
  flex-direction: column;
  margin-bottom: 50px;
}

#movieInfoAndBuyTicket {
  width: 20%;
}


#rowNumShow {
  display: flex;
  flex-direction: column;
  float: left;
}

#rowNumShow .el-text {
  margin: 19px auto;
}

#seatAll {
  margin: 0 50px;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  align-content: space-around;
}

#seatAll .el-image {
  margin: 12px 40px 12px 40px;
}

#selectSeatList {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  align-content: space-around;
}

.ticketDiv {
  width: 90px;
  margin: 10px 10px;
  background: radial-gradient(10% 7px at center left, transparent 100%, #48e11e 0) center left;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
}
</style>